import React, { createContext, useContext, useReducer } from "react"
import { AppState, EAction } from "./contextType"
import { produce } from "immer"

const initState: AppState = {
  userInfo: {},
}

const appReducer = (state: AppState, action: EAction): AppState => {
  const { type, payload } = action
  return produce(state, (draft) => {
    switch (type) {
      case "initUser":
        draft.userInfo = payload
        break
      default:
        console.warn("unexcepted Action", action)
        break
    }
  })
}

export const useAppContext = () => {
  return useContext(AProvider)
}
const AProvider = createContext<{
  state: AppState
  dispatch: React.Dispatch<EAction>
}>({ state: initState, dispatch: (action: EAction) => void 0 })

export const AppProvider = ({ children }: any) => {
  const [state, dispatch] = useReducer(appReducer, initState)
  return (
    <>
      <AProvider.Provider value={{ state, dispatch }}>
        {children}
      </AProvider.Provider>
    </>
  )
}
